<?php
require_once 'Zend/Db.php';
require_once 'Zend/Config/Ini.php';
class hostshelper{
	private $config;
	private $memcache;
	function __construct(){
		$this->config = new Zend_Config(require 'inc/dbcnf.php');
		$this->memcache = new Memcache;
		$this->memcache->connect($this->config->memcache->host, $this->config->memcache->port);
	}
	private function db_cacti(){
		return Zend_Db::factory($this->config->db_cacti);
    }
    private function db_mwall(){
		return Zend_Db::factory($this->config->db_mwall);
    } 
    private function db_131(){
		return Zend_Db::factory($this->config->db_131);
    }
	private function db_vod_stat(){
        return Zend_Db::factory($this->config->db_vod_stat);
    } 
    private function db_live_stat(){
        return Zend_Db::factory($this->config->db_live_stat);
    }  
	public function area_band_used(){
		$dbmwall = $this->db_mwall();
		$db131 = $this->db_131();
		$db_vod_stat = $this->db_vod_stat();
		$db_live_stat = $this->db_live_stat();
		$idarea = $dbmwall->fetchAll("select hostip as id,area1 from hosts");
		$idareamap = array();
		foreach($idarea as $item){
			$idareamap[$item["id"]]=$item["area1"];
		}
		$bands = $db131->fetchAll("select b.VDG_NAME as name,band from (select sum(VDG_INPLACE_BAND)*1024*1024 as band,VDG_PARENTID as pid from vlog_device_group where VDG_DELETETYPE=0 and VDG_TYPE=0 group by VDG_PARENTID )a left join vlog_device_group b on a.pid = b.VDG_ID where b.VDG_NAME is not null");
		$bands_vod_used = $db_vod_stat->fetchAll("select VRS_SCSIP as id, sum(VRS_DISPENSE_FLUX) as vod from vlog_report_scs group by VRS_SCSIP");
		$bands_live_used = $db_live_stat->fetchAll("select VRS_SCSIP as id, sum(VRS_DISPENSE_FLUX) as live from vlog_report_scs group by VRS_SCSIP");
		$r = array();
		foreach($bands as $item){
			$r[$item["name"]]["area1"] = $item["name"];
			$r[$item["name"]]["bands"] = $item["band"];
			$r[$item["name"]]["vod"] = 0;
			$r[$item["name"]]["live"] = 0;
			$r[$item["name"]]["percent"] = 0;
		}
		foreach($bands_vod_used as $item){
			$areaname = $idareamap[$item["id"]];
			$r[$areaname]["vod"] += $item["vod"];
		}
		foreach($bands_live_used as $item){
			$areaname = $idareamap[$item["id"]];
			$r[$areaname]["live"] += $item["live"];
		}
		$result = array();
		foreach($r as $k=>$item){
			if($item["bands"]>0){
				$item["percent"] = ceil(100*($item["vod"]+$item["live"])/$item["bands"]);
				$result[$k] = $item;
			}
		}
		foreach($result as $k=>$row){
			 $percent[$k]  = $row['percent'];
		}	
		array_multisort($percent, SORT_DESC, $result);
		$jsonbandused = json_encode($result);
		$this->memcache->set("mwall_band_used",$jsonbandused);
	}
	public function hosts_errornum(){
		$db_cacti = $this->db_cacti();
		$devrows = $db_cacti->fetchAll("select hostname, min(type) as type from(
					select hostname ,'1' type from host where status =1 union
					select hostname ,'2' type from poller_output_v where output <>1 and rrd_name='TCP')s group by s.hostname");
		$filter = "''";
		$errortypes = array();
		foreach($devrows as $row){
			$filter .= ",'".$row["hostname"]."'";
			$errortypes[$row["hostname"]]=$row["type"];
		}
		$db_mwall = $this->db_mwall();
		$ehosts0 = $db_mwall->fetchAll("select devid, hostip, area1, area2,hosttypes.name from hosts left join hosttypes on hosts.hosttypeid = hosttypes.id where hide=0 and area1 is not null and  hostip in($filter)");
		$hostarea0 = $db_mwall->fetchAll("select  area1,count(hostip) as num,0 as errornum from hosts where hide =0 and area1 is not null group by area1");
		$hostarea = array();
		if (!empty($hostarea0))
	    {
	        foreach ($hostarea0  as $item)
	        {
	            $hostarea[$item['area1']]["num"] = $item['num'];
	            $hostarea[$item['area1']]["errornum"] = $item['errornum'];
	        }
	    }
		$ehosts = array();
		foreach($ehosts0 as $ehost){
			$ehost["type"] = $errortypes[$ehost["hostip"]];
			$ehosts[] = $ehost;
			$hostarea[$ehost["area1"]]["errornum"]+=1;
		}
		$jsonhostarea = json_encode($hostarea);
		$jsonehosts = json_encode($ehosts);
		$this->memcache->set("mwall_hosts_area",$jsonhostarea);
		$this->memcache->set("mwall_hosts_down_list",$jsonehosts);
	}
	private function hosts_stats_bytype($type,$memkey){
		$db_cacti = $this->db_cacti();
        $db_mwall = $this->db_mwall();
		$hosts = $db_mwall->fetchAll("select hostip from hosts left join hosttypes on hosts.hosttypeid = hosttypes.id where hosttypes.tpl = :type",array("type"=>$type));	
		$array_hosts = array();
		foreach($hosts as $host){
			$hostrow = $db_cacti->fetchRow("select hostname, output from poller_output_v where rrd_name = 'TCP' and hostname = :hostname",array("hostname"=>$host["hostip"]));
			if($hostrow)
				$array_hosts[] = $hostrow;
        }
		$jsonhosts = json_encode($array_hosts);
		$this->memcache->set($memkey,$jsonhosts);
	}
	private function sbs_stat($memkey){
		$db_131 = $this->db_131();	
		$result = $db_131->fetchAll("SELECT VB_USERIP as VB_NAME,VB_ZBHASQGWD,VB_DBHASQGWD,VB_ZBSTATE,VB_DBSTATE FROM vlog_balance v where vb_deletetype=0  and DATEDIFF(now(),VB_TXTIME)=0");
		$json_sbs_stat = json_encode($result); 
		$this->memcache->set($memkey,$json_sbs_stat);
	}	
	public function hosts_stats(){
		$this->hosts_stats_bytype("soooner-db","mwall_hosts_db_list");
		$this->hosts_stats_bytype("soooner-auth","mwall_hosts_auth_list");
		$this->hosts_stats_bytype("soooner-gslb","mwall_hosts_gslb_list");
		$this->hosts_stats_bytype("soooner-data","mwall_hosts_data_list");
		$this->hosts_stats_bytype("soooner-dns","mwall_hosts_dns_list");
		$this->sbs_stat("mwall_hosts_sbs_health_list");
	}
	public function current_stats(){
		$db_live_stat = $this->db_live_stat();
		$live_stats = $db_live_stat->fetchRow("select sum(VRS_DISPENSE_FLUX) bandwidth,sum(VRS_CURLINK_NUM) online from vlog_report_scs");
		if($live_stats){
			$this->memcache->set("mwall_live_online", $live_stats["online"]);
			$this->memcache->set("mwall_live_bandwidth", $live_stats["bandwidth"]);
		}
		$live_stats_sp = $db_live_stat->fetchAll("select VRS_LOGINID sp,sum(VRS_DISPENSE_FLUX) bandwidth,sum(VRS_CURLINK_NUM) online from vlog_report_scs group by VRS_LOGINID");
		foreach($live_stats_sp as $item){
			$this->memcache->set("mwall_".$item["sp"]."_live_online", $item["online"]);
			$this->memcache->set("mwall_".$item["sp"]."_live_bandwidth", $item["bandwidth"]);
			echo "mwall_".$item["sp"]."_live_bandwidth";
		}
		$db_vod_stat = $this->db_vod_stat();
		$vod_stats = $db_vod_stat->fetchRow("select sum(VRS_DISPENSE_FLUX) bandwidth,sum(vrs_view_num) online from vlog_report_scs");
		if($vod_stats){
            $this->memcache->set("mwall_vod_online", $vod_stats["online"]);
            $this->memcache->set("mwall_vod_bandwidth", $vod_stats["bandwidth"]);
        }   
		$vod_stats_sp = $db_vod_stat->fetchAll("select VRS_LOGINID sp,sum(VRS_DISPENSE_FLUX) bandwidth,sum(vrs_view_num) online from vlog_report_scs group by VRS_LOGINID");
		foreach($vod_stats_sp as $item){
            $this->memcache->set("mwall_".$item["sp"]."_vod_online", $item["online"]);
            $this->memcache->set("mwall_".$item["sp"]."_vod_bandwidth", $item["bandwidth"]);
        } 
		//webcache
        $c = file_get_contents("http://211.100.48.159/api/get_last_value.php?rrd=total&start=now-30m&end=now-20m&ds=client_bytes_out,client_requests");
		preg_match("/<v>(.*?)<\/v>.*?<v>(.*?)<\/v>/im", $c, $matches);
		if(count($matches)==3){
		        $this->memcache->set("mwall_web_online",1*$matches[2]);
		        $this->memcache->set("mwall_web_bandwidth",1*$matches[1]);
		}
		$webSps = array("SWS001","SWS002");
		foreach($webSps as $webSp){
			$c = file_get_contents("http://211.100.48.159/api/get_last_value.php?rrd=bizuser/$webSp&start=now-30m&end=now-20m&ds=client_bytes_out,client_requests");
			preg_match("/<v>(.*?)<\/v>.*?<v>(.*?)<\/v>/im", $c, $matches);
			if(count($matches)==3){
			        $this->memcache->set("mwall_".$webSp."_web_online",1*$matches[2]);
			        $this->memcache->set("mwall_".$webSp."_web_bandwidth",1*$matches[1]);
			}
		}        
	}
	public function sync_output_v(){
		$db_cacti = $this->db_cacti();
		$devrows = $db_cacti->query("insert  into poller_output_v(local_data_id,rrd_name,hostname) select  poller_item.local_data_id,poller_item.rrd_name,poller_item.hostname from poller_output_v right join poller_item on poller_output_v.local_data_id = poller_item.local_data_id and poller_output_v.rrd_name = poller_item.rrd_name where poller_output_v.local_data_id is null");
	}
}
$hostshelper = new hostshelper();
$hostshelper->hosts_errornum();
$hostshelper->hosts_stats();
$hostshelper->area_band_used();
$hostshelper->current_stats();
$hostshelper->sync_output_v();

